<template>
  <div>
    <resize-by-drag class="resize_by_drag" @show="boxShow" @resize="resize" @resetSize="resetSize" ref="resizeLayout"
                    :init-page-data.sync="pageData">
      <div slot="container_left">
        <div class="slot_item">
          <evidence-catalog-tree @clear-checked="clearChecked" @node-click="evidenceClick"
                                 ref="evidenceCatalogTree"></evidence-catalog-tree>
        </div>
      </div>
      <div slot="container_center">
        <div class="slot_item zjcl_box">
          <div class="nav" :style="skin.style.nav">
            <div class="nav_item" :style="selected===2?skin.style.nav_item_selected:''" @click="centerSwitch(2)">电子卷宗
            </div>
            <div class="nav_item" :style="selected===3?skin.style.nav_item_selected:''" @click="centerSwitch(3)">文书卷宗
            </div>
            <div class="nav_item" :style="selected===1?skin.style.nav_item_selected:''" @click="centerSwitch(1)">预&nbsp;&nbsp;&nbsp;案</div>
          </div>
          <doc-view v-show="selected===1" style="height: calc(100% - 40px)" @drop-end="clearChecked"
                    @zjcl-click="zjclClick" ref="docView"></doc-view>
          <div v-show="selected===2" style="height: calc(100% - 40px);">

            <dossier-tree
              ref="dossierTree"
              :show-checkbox="true"
              :show-delete="!isBrowser"
              @node-click="nodeClick"
              @rootNodeChanged="rootNodeChange"></dossier-tree>

            <!--<el-input placeholder="输入关键字进行检索" size="mini" style="width:calc(100% - 20px);margin:5px 10px;font-size: 14px" v-model="filterText">-->
            <!--</el-input>-->
            <!--<el-tree class="dossierTree" ref="dossierTree" :data="dossierTreeDataSource" node-key='NodeID' @node-click="nodeClick" @check="check" :render-content="renderContent" :filter-node-method="filterNode" :expand-on-click-node="!(pressCtrlKey||pressShiftKey)" :highlight-current="true" :show-checkbox="true">-->
            <!--&lt;!&ndash; lazy :load="loadChildrenNode" &ndash;&gt;-->
            <!--</el-tree>-->
          </div>
          <div v-show="selected===3" style="height: calc(100% - 40px);">
            <el-input placeholder="输入关键字进行检索" size="mini"
                      style="width:calc(100% - 20px);margin:5px 10px;font-size: 14px" v-model="filterText">
            </el-input>
            <el-tree class="dossierTree" ref="docDossierTree" node-key='NodeID' @node-click="nodeClick" @check="check"
                     :data="docDossierTreeDataSource" :render-content="renderContent" :filter-node-method="filterNode"
                     :expand-on-click-node="!(pressCtrlKey||pressShiftKey)" :highlight-current="true"
                     :show-checkbox="true">
            </el-tree>
          </div>
        </div>
      </div>
      <div slot="container_right">
        <div class="slot_item">
          <div class="nav_right" :style="skin.style.nav_right">
            <div class="nav_right_item" :style="editType===2?skin.style.nav_right_item_selected:''"
                 :class="{nav_right_item_selected:editType===2}" @click="editType=2">证据预览
            </div>
            <div class="nav_right_item" :style="editType===1?skin.style.nav_right_item_selected:''"
                 :class="{nav_right_item_selected:editType===1}" @click="editType=1">证据编辑
            </div>
          </div>
          <div v-show="editType===1"
               style="height:calc(100% - 40px);background-color: #fff;overflow:hidden;position: relative;">
            <div style="height:67px;color:green;border-bottom:1px solid #e1e1e1;">
              <slide-toolbar/>
            </div>
            <div ref="aa" style="height:calc(100% - 67px)">
              <slide-editor ref="editor" :expandScreen="false"></slide-editor>
            </div>
          </div>
          <pre-zjcl v-show="editType===2" class="PreZjcl" ref="PreZjcl" style="height:calc(100% - 30px)"></pre-zjcl>

          <div v-show="editType===2" class="btn_control left" @click="currPage('prev')"></div>
          <div v-show="editType===2" class="btn_control right" @click="currPage('next')"></div>
        </div>
      </div>
    </resize-by-drag>
    <div ref="cursor" class="cursor_div">
      <div ref="cursor_img" class="cursor_img"></div>
      <div class="cursor_text nowrap">{{cursor_text}}</div>
    </div>

    <vmodal :modalshow="modalshow" modaltitle="加入示证大纲" :closeonclickmodal="false"
            :styleobj="{width: '300px',height: '437px'}" @hide="modalshow=false">
      <div slot="modal" style="width:100%;height:100%;background-color: white">
        <div style="width:100%;height:calc(100% - 50px);overflow: auto;">
          <el-tree ref="catalogMLTree" highlight-current render-after-expand node-key='id' :data="catalogML"
                   :props="catalogProps" style="width:100%">
          </el-tree>

          <!-- default-expand-all -->
        </div>
        <div style="text-align: right;height: 50px">
          <el-button style="margin:5px 10px 0 0" size="small" type="plain" @click="cancelAddMindMapping">取消
          </el-button>
          <el-button style="margin:5px 10px 0 0" size="small" type="primary" @click="addMindMapping">确认
          </el-button>
        </div>
      </div>
    </vmodal>

  </div>
</template>

<script>
  import {mapState, mapActions, mapGetters} from 'vuex'
  import {action, mutation} from '../common/quantity'
  import evidenceCatalogTree from '../config/evidenceCatalogTree'

  import actions from '../common/typeActions'
  import commonServer from '../server/common/commonServer'

  import events from '../common/typeEvents'
  import SQLite from '../common/SQLiteHelper'
  import DossierTree from '../components/DossierTree'

  const path = require('path')
  const skin = require('../config/skin')
  let remote = {}
  try {
    remote = require('electron').remote
  } catch (e) {
  }

  const {
    util: {getTreeNodes, getBase64},
    CMD: {openDirOrFile}
  } = require('../util')

  export default {
    name: 'PrePlan',
    components: {DossierTree},
    data () {
      return {
        isBrowser: process.browser,
        pageData: {},
        currentNode: {},
        selected: 2,
        editType: 2,
        filterText: '',
        fileDataSourceIndex: 0,
        docFileDataSourceIndex: 0,
        skin: skin[skin.useSkin],
        pressShiftKey: false,
        pressCtrlKey: false,
        lastCheckedNode: {},
        cursor_text: '',
        modalshow: false,
        catalogProps: {
          children: 'children',
          label: 'alias'
        },
        catalogML: []
      }
    },
    computed: {
      ...mapState({
        casePath: state => state.appearCourt.casePath,
        caseInfo: state => state.appearCourt.caseInfo,
        retrieveDataSource: state => state.appearCourt.retrieveDataSource,
        dossierDataSource: state => state.appearCourt.dossierDataSource,
        dossierTreeDataSource: state =>
          JSON.parse(JSON.stringify(state.appearCourt.dossierTreeDataSource)),
        docDossierDataSource: state => state.appearCourt.docDossierDataSource,
        docDossierTreeDataSource: state =>
          JSON.parse(JSON.stringify(state.appearCourt.docDossierTreeDataSource)),
        isMergeDir: state => state.common.preplanOptions.isMergeDir,
        slide: state => state.slideEditor.slide
      }),
      ...mapGetters({
        fileDataSource: 'fileDataSource',
        docFileDataSource: 'docFileDataSource'
        // ,catalogML: 'catalogML'
      })
    },
    watch: {
      filterText (newVal, oldVal) {
        this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree'].filter(
          newVal
        )
      },
      editType: function (n, o) {
        if (n === 1) {
          this.$nextTick(() => {
            let dom = this.$refs.aa
            this.$refs.editor.initContainer(dom)
          })
        }
      },
      'slide.id': function (n, o) {
        let docView = this.$refs.docView
        if (n !== o && docView) docView.setStyle(n)
      }
    },
    async mounted () {
      let selected = 2
      let leftShow = false
      let isPlay = false
      this.$eventBus.$on(events.SlideEditor.SlideStateChanged, data => {
        if (data) {
          if (isPlay) return
          console.log('开始放映')
          leftShow = this.$refs.resizeLayout
            ? this.$refs.resizeLayout.isShow('container_left')
            : false
          if (
            this.$refs.resizeLayout &&
            !this.$refs.resizeLayout.isShow('container_center')
          ) {
            this.$refs.resizeLayout &&
            this.$refs.resizeLayout.show('container_center')
          }
          selected = this.selected
          this.centerSwitch(1)
          this.$refs.resizeLayout &&
          this.$refs.resizeLayout.hide('container_left')
          isPlay = true
        } else {
          console.log('结束放映')
          this.centerSwitch(selected)
          let docView = this.$refs.docView
          if (docView) docView.setStyle()
          if (leftShow) {
            if (this.$refs.resizeLayout) {
              this.$refs.resizeLayout.show('container_left')
            }
          }
          isPlay = false
        }
      })

      this.$eventBus.$on('keyup', ev => {
        if (ev.key === 'Shift') this.pressShiftKey = false
        if (ev.key === 'Control') this.pressCtrlKey = false
      })
      this.$eventBus.$on('keydown', ev => {
        if (ev.key === 'Shift') this.pressShiftKey = true
        if (ev.key === 'Control') this.pressCtrlKey = true
      })

      this.showPdf()
    },
    created () {
      this.readLayout()
      this.$store.dispatch(action.preplan.initPrePlan).catch(async e => {
        console.error(e)
        await this.$alert(e.message, '错误', {type: 'error'})
        this.closeCase()
      })
    },
    methods: {
      ...mapActions({
        initSlide: actions.SLIDEEDITOR.InitSlide
      }),
      //     loadChildrenNode:function(node,resolve){
      //       console.log(node)
      //       console.log(this.$store.state.appearCourt.dossierDataSource)
      //       if(node.level==0){
      // resolve(this.$store.state.appearCourt.dossierDataSource.filter(x=>{return x.NodeParentID == ''}) )
      //       }else{
      // resolve(this.$store.state.appearCourt.dossierDataSource.filter(x=>{return x.NodeParentID == node.data.NodeID}) )
      //       }
      //       //   if(node.level!=0 && !node.data.children)return resolve([])
      //       //   resolve(node.level==0?this.dossierTreeDataSource:node.data.children)
      //       },
      cancelAddMindMapping () {
        this.modalshow = false
        this.$refs.catalogMLTree && this.$refs.catalogMLTree.setCurrentNode({})
      },
      addMindMapping () {
        let tree = this.$refs.catalogMLTree
        if (!tree) return
        let node = tree.getCurrentNode()
        tree.setCurrentNode({})
        if (!node) {
          return this.$alert('没有选中节点', '提示', {type: 'warning'})
        }

        let srcTree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']

        let transferData = srcTree
          .getCheckedNodes()
          .filter(x => x.FileType === 'file')

        if (!transferData.length) transferData.push(this.currentNode.data)

        // 获取所有的文件节点的父节点
        transferData.forEach(item => {
          let node = srcTree.getNode(item)
          if (!node.parent) return
          while ((node = node.parent)) {
            let pnode = node.data
            let isExist = transferData.some(
              _item => _item.NodeID === pnode.NodeID
            )
            if (!isExist) transferData.push(pnode)
            if (pnode.FileType === 'dir') break
          }
        })

        let data = {node: node, dossiers: JSON.stringify(transferData)}

        this.$eventBus.$emit('ADD_FILES_INTO_CATALOG', data)

        this.modalshow = false
      },
      zjclClick (nodeID) {
        console.log('点击了：', nodeID)
        this.$refs.evidenceCatalogTree.setSelectedNode(nodeID)
      },
      centerSwitch (selected) {
        this.selected = selected
        if (selected === 1) return
        this.filterText = ''
        this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree'] &&
        this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree'].filter()
        this.showPdf()
      },
      rootNodeChange (nodeid) {
        if (!this.fileDataSource.length) return
        this.$nextTick(() => {
          this.setSelectedNode(this.fileDataSource[0].NodeID)
        })
      },
      currPage (type) {
        if (this.selected !== 2 && this.selected !== 3) return
        let index = this.selected === 2 ? this.fileDataSourceIndex : this.docFileDataSourceIndex
        let rootID = this.selected === 2 ? this.$refs.dossierTree.currDossierID : null
        if (type === 'prev') {
          if (this.$store.getters.isFirstNode(rootID, index - 1)) {
            return this.$message('当前已经是第一页')
          } else {
            this.fileDataSourceIndex = index--
          }
        } else {
          if (this.$store.getters.isLastNode(rootID, index + 1)) {
            return this.$message('当前已经是最后一页')
          } else {
            this.docFileDataSourceIndex = index++
          }
        }

        let nodeid = this[this.selected === 2 ? 'fileDataSource' : 'docFileDataSource'][index].NodeID
        if (!nodeid) return
        this.setSelectedNode(nodeid)
        // return;
        //
        // if (this.selected !== 2 && this.selected !== 3) return;
        // if (type === "prev") {
        //   this[
        //     this.selected === 2 ? "fileDataSourceIndex" : "docFileDataSourceIndex"
        //     ] -= 1;
        //   if (
        //     this[
        //       this.selected === 2
        //         ? "fileDataSourceIndex"
        //         : "docFileDataSourceIndex"
        //       ] < 0
        //   ) {
        //     this[
        //       this.selected === 2
        //         ? "fileDataSourceIndex"
        //         : "docFileDataSourceIndex"
        //       ] = 0;
        //     return this.$message("当前已经是第一页");
        //   }
        // } else {
        //   this[
        //     this.selected === 2 ? "fileDataSourceIndex" : "docFileDataSourceIndex"
        //     ] += 1;
        //   if (
        //     this[
        //       this.selected === 2
        //         ? "fileDataSourceIndex"
        //         : "docFileDataSourceIndex"
        //       ] >
        //     this[this.selected === 2 ? "fileDataSource" : "docFileDataSource"]
        //       .length -
        //     1
        //   ) {
        //     this[
        //       this.selected === 2
        //         ? "fileDataSourceIndex"
        //         : "docFileDataSourceIndex"
        //       ] =
        //       this[this.selected === 2 ? "fileDataSource" : "docFileDataSource"]
        //         .length - 1;
        //     return this.$message("当前已经是最后一页");
        //   }
        // }
        // let id = this[
        //   this.selected === 2 ? "fileDataSource" : "docFileDataSource"
        //   ][
        //   this[
        //     this.selected === 2 ? "fileDataSourceIndex" : "docFileDataSourceIndex"
        //     ]
        //   ].NodeID;
        // if (!id) return;
        // this.setSelectedNode(id);
      },
      /**
       * 根据id展开自身及父节点
       */
      expandNode (id) {
        try {
          console.group(`展开节点【${id}】`)
          let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
          let node = tree.getNode(id)
          if (!node) return console.log(`未找到id为【${id}】的节点`)
          console.log(`已找到节点`, node.data.MLXSMC)
          let _node = node
          _node.expand()
          while ((_node = _node.parent)) {
            _node.expand()
          }
          console.log('已展开到指定节点')
          let el = document.querySelector(`.zjcl_box .node_${id}`)
          this.$nextTick(() => {
            if (el) {
              el.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
                inline: 'nearest'
              })
            }
            // el && el.scrollIntoView();
          })
        } finally {
          console.groupEnd()
        }
      },
      setSelectedNode (id) {
        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        if (!tree) return
        let node = tree.getNode(id)
        if (!node) return
        this.nodeClick(node.data, node)
      },
      evidenceClick (data, node) {
        if (Number(data.type) === 0) return

        let docView = this.$refs.docView

        if (docView) docView.setStyle(data.id)

        this.initSlide(node)
        this.editType = 1
      },
      async deleteNode (type, data) {
        try {
          let checkedNodes = []
          let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
          if (!tree) return
          if (!type) {
            checkedNodes = getTreeNodes([data])
          } else if (type === 'file') {
            checkedNodes = tree
              .getCheckedNodes()
              .filter(node => node.FileType === 'file')
          } else if (type === 'dir') {
            checkedNodes = tree.getCheckedNodes()
          }

          await this.$confirm('是否删除?', '提示')
          await this.$store.dispatch(action.preplan.DelDossierFile, {
            nodes: checkedNodes,
            type: this.selected === 2 ? 'dossier' : 'docDossier'
          })
          this.delfun(checkedNodes)
          tree.setCheckedNodes([])

          let sendData = {}
          if (this.selected === 2) {
            sendData.dossierTreeDataSource = this.dossierTreeDataSource
          } else if (this.selected === 3) {
            sendData.docDossierTreeDataSource = this.docDossierTreeDataSource
          }

          this.$store.commit(mutation.appearCourt.setData, sendData)
        } catch (e) {
          console.error(e)
        }
      },
      delfun (nodes) {
        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        nodes.forEach(node => {
          if (tree) tree.remove(node)
        })
      },
      async exportSelectFile () {
        try {
          let win = remote.BrowserWindow.getFocusedWindow()
          let res = remote.dialog.showSaveDialog(win, {
            title: '导出文件内容',
            defaultPath: `${this.caseInfo.AJMC}-文件内容`,
            filters: [
              {
                name: 'Word',
                extensions: ['doc']
              }
            ]
          })
          if (!res) return

          this.loadStatus({loading: true, loadingText: '导出中'})
          let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']

          if (!tree) {
            return this.$alert('删除失败', '错误', {type: 'error'})
          }

          let checkedNodes = [
            ...tree.getCheckedNodes(),
            ...tree.getHalfCheckedNodes()
          ]
          let files = checkedNodes.filter(item => item.FileType === 'file')
          files = JSON.parse(JSON.stringify(files))
          tree.setCheckedNodes([])
          let box = document.createElement('div')
          let titleP = document.createElement('p')
          titleP.style.textAlign = 'center'
          let title = document.createElement('span')
          title.innerHTML = `<strong>${this.caseInfo.AJMC}-文件内容</strong>`
          title.style.fontSize = '24pt'
          titleP.appendChild(title)
          box.appendChild(titleP)
          files.forEach(item => {
            let parent = checkedNodes.find(
              _item => _item.NodeID === item.NodeParentID
            )
            if (parent) item.MLXSMC = `${parent.MLXSMC}(${item.MLXSMC})`

            let p = document.createElement('p')

            let fileName = document.createElement('span')
            fileName.innerText = item.MLXSMC

            fileName.style.display = 'inline-block'
            fileName.style.color = 'blue'
            fileName.style.fontSize = '14pt'
            fileName.style.cursor = 'pointer'
            fileName.style.textDecoration = 'underline'

            fileName.className = 'MsoHyperlink'
            fileName.innerText = item.MLXSMC
            fileName.title = item.MLXSMC

            let node = this.retrieveDataSource.find(
              _item => _item.WJBH === item.ID
            )

            let span = document.createElement('span')
            span.innerText = `【${node ? node.TEXT : ''}】`
            span.style.fontSize = '14pt'

            p.appendChild(fileName)
            p.appendChild(span)
            // insertAfter(fileName, span);
            box.appendChild(p)
          })

          let html = box.innerHTML
          html = html.replace(/<title><\/title>/gi, '')
          html = `<!DOCTYPE html>
                  <html lang="en">
                    <head>
                      <meta charset="UTF-8">
                      <meta http-equiv="content-type" content="application/msword;charset=utf-8">
                    </head>
                    <body style="font-family: 仿宋;font-size: 12pt">
                      ${html}
                  </body>
                </html>`

          let result = await SQLite.HtmlExportWord({
            html: Buffer.from(html, 'UTF-8'),
            filePath: res
          })

          if (result) {
            try {
              await this.$confirm('导出成功，是否打开？', '提示')
              openDirOrFile(res)
            } catch (e) {
              console.log(e)
            }
          } else {
            this.$alert('失败原因：' + result, '导出失败', {type: 'error'})
          }
        } catch (e) {
          console.error(e)
          this.$alert('失败原因：' + e.message, '导出失败', {type: 'error'})
        } finally {
          this.loadStatus({loading: false})
        }
      },
      /**
       * 树节点右键事件
       * 右键弹出菜单
       */
      nodeContextmenu (ev, data, node, c) {
        this.currentNode = node
        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        // let isRoot = node.level === 1
        let isFile = data.FileType === 'file'
        let isDir = data.FileType === 'dir'
        let isMulti = tree ? tree.getCheckedNodes().length > 0 : false
        let hasFile = tree
          ? tree.getCheckedNodes().filter(x => x.FileType === 'file').length > 0
          : false

        if (isMulti) {
          // isRoot = false
          isFile = false
          isDir = false
        }

        let contextmenu = [
          {
            label: '删除',
            icon: getBase64('/img/catalog/04.png'),
            show: isDir || isFile,
            click: async () => {
              await this.deleteNode('', data)
              this.expandNode(data.NodeParentID)
            }
          },
          {
            label: '删除选中文件',
            icon: getBase64('/img/catalog/delfile.png'),
            show: isMulti,
            click: async () => {
              await this.deleteNode('file')
              this.expandNode(data.NodeParentID)
            }
          },
          {
            label: '删除选中目录及文件',
            icon: getBase64('/img/catalog/delfolder.png'),
            show: isMulti,
            click: async () => {
              await this.deleteNode('dir')
              this.expandNode(data.NodeParentID)
            }
          },
          {
            label: '导出选中文件内容',
            icon: getBase64('/img/catalog/dc.png'),
            show: isMulti && this.skin.contextmenu.exportSelectFile,
            click: this.exportSelectFile
          },
          {
            label: '加入示证目录',
            icon: getBase64('/img/catalog/dc.png'),
            show: isFile || hasFile,
            click: ev => {
              this.catalogML = evidenceCatalogTree.getCatalogML()
              this.modalshow = true
            }
          }
        ]
        this.contextMenuShow(ev, contextmenu)
      },
      dossierTreeNodeClick (data, node) {
        console.log('有节点被点击了', data, node)
      },
      /**
       * tree 树节点点击事件
       * @param data
       * @param node
       * @param c
       * @param ev
       */
      async nodeClick (data, node, c, ev = event) {
        /**
         * 去除所有的子节点
         * @param nodes
         * @param pid
         */
        function clearChildNodeByPid (nodes = [], pid) {
          for (let i = 0; i < nodes.length; i++) {
            let node = nodes[i]
            if (node.NodeParentID === pid) {
              if (node.children) {
                clearChildNodeByPid(nodes, node.NodeID)
              }
              nodes.splice(i, 1)
              i--
            }
          }
          return nodes
        }

        /**
         * 获取按住Ctrl时需要勾选的node
         * @param nodes 目前所有选中的节点
         * @param node 需要操作的节点
         * @param cheched 是否选中
         */
        function getCtrlNodes (nodes = [], node, cheched) {
          let index = nodes.findIndex(_node => _node.NodeID === node.NodeID)
          let isExist = index > -1
          if (cheched) {
            if (!isExist) nodes.push(node)
          } else {
            if (isExist) nodes.splice(index, 1)
          }
          return nodes
        }

        /**
         * 获取按住Shift时需要勾选的node
         * @param id1 其中一个ID
         * @param id2 其中一个ID
         * @param treeNodes 数据源
         * @returns {Array}
         */
        let getShiftNodes = (id1, id2, treeNodes = []) => {
          let nodes = []
          let index1 = treeNodes.findIndex(item => item.NodeID === id1)
          let index2 = treeNodes.findIndex(item => item.NodeID === id2)

          if (index2 === -1) index2 = 0
          if (index1 < 0) return nodes
          if (index1 > index2) {
            let temp = index2
            index2 = index1
            index1 = temp
          }
          for (let i = index1; i <= index2; i++) {
            let node = treeNodes[i]
            if (i !== index2 && node.children && node.children.length) continue
            let isExist =
              nodes.findIndex(item => item.NodeID === node.NodeID) > -1
            if (isExist) continue
            nodes.push(node)
          }
          return nodes
        }

        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        let nodes = tree.getCheckedNodes() // 当前所有的选中节点

        if (ev && ev.ctrlKey) {
          this.lastCheckedNode = data
          let p = node
          while ((p = p.parent)) {
            if (p.checked) {
              nodes = nodes.filter(item => item.NodeID !== p.data.NodeID)
            }
          }
          nodes = clearChildNodeByPid(nodes, data.NodeID)
          tree.setCheckedNodes(getCtrlNodes(nodes, data, !node.checked))
          return
        }
        if (ev && ev.shiftKey) {
          let preSetNodes = getShiftNodes(
            data.NodeID,
            this.lastCheckedNode.NodeID,
            this[this.selected === 2 ? 'dossierDataSource' : 'docDossierDataSource']
          )
          tree.setCheckedNodes(preSetNodes)
          return
        }

        if (data.FileType !== 'file') return

        try {
          this.loadStatus({loading: true, loadingText: '正在获取证据材料，请稍等'})
          let index = this[this.selected === 2 ? 'fileDataSource' : 'docFileDataSource'].findIndex(item => item.ID === data.ID)
          if (index === -1) return
          this[this.selected === 2 ? 'fileDataSourceIndex' : 'docFileDataSourceIndex'] = index
          await this.showPdf()
          this.editType = 2
          console.log('点击了证据树节点', data)
        } finally {
          this.loadStatus({loading: false})
        }
      },
      check (data) {
        this.lastCheckedNode = data
      },
      async showPdf () {
        let node = {}
        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        if (this.selected === 2) {
          node = this.fileDataSource[this.fileDataSourceIndex]
          if (node && tree) tree.setCurrentNode(node)
        } else if (this.selected === 3) {
          node = this.docFileDataSource[this.docFileDataSourceIndex]
          if (node && tree) tree.setCurrentNode(node)
        }
        if (!node) return
        this.expandNode(node.NodeID)
        let base64 = null
        if (process.browser) {
          base64 = await this.$api.post.getEvidenceMaterialByCode({
            fileID: node.NodeID,
            fileType: this.selected === 2 ? 0 : 1,
            dbPath: this.$store.state.appearCourt.casePath
          })
        } else {
          base64 = await commonServer.getPDFFileByID(node.ID)
        }
        if (/mp3|mp4/i.test(node.WJKZM || node.WJHZ)) {
          const {dir, name} = path.parse(this.casePath)
          base64 = path.resolve(dir, name, base64)
        }
        this.$refs.PreZjcl.show(base64)
      },
      filterNode (value, data, node) {
        if (!value) return true
        if (node.level > 1 && node.parent.visible) return true
        return data.MLXSMC.indexOf(value) !== -1
      },
      pointermove (ev) {
        ev.returnValue = false
        if (ev.pointerType === 'touch') return

        let el = ev.target
        let isEvidenceCatalogTree = el.classList.contains('evidenceCatalogTree')
        if (!isEvidenceCatalogTree) {
          while ((el = el.parentElement)) {
            if (el.classList.contains('evidenceCatalogTree')) {
              isEvidenceCatalogTree = true
              break
            }
          }
        }

        let div = this.$refs.cursor
        let cursorImg = this.$refs.cursor_img
        let x = ev.screenX - window.screenX
        let y =
          ev.screenY -
          window.screenY -
          10 -
          (window.outerHeight - window.innerHeight)
        x = x - div.offsetWidth / 2
        div.style.left = `${x}px`
        div.style.top = `${y}px`
        div.style.visibility = `visible`
        if (isEvidenceCatalogTree) {
          cursorImg.style.backgroundImage = `url('${getBase64(
            '/img/able.png'
          )}')`
        } else {
          cursorImg.style.backgroundImage = `url('${getBase64(
            '/img/disable.png'
          )}')`
        }
      },
      pointerdown (ev, node, data) {
        if (ev.pointerType === 'touch') return
        if (ev.button !== 0) {
          if (ev.button === 2) {
            ev.stopPropagation()
            this.nodeContextmenu(ev, data, node)
          }
          return
        }

        this.isPointerdown = true
        this.isPointerout = false
        console.log('pointerdown')

        let pointerup = ev => {
          this.isPointerdown = false
          this.isPointerout = false
          console.log('pointerup')
          let div = this.$refs.cursor
          div.style.visibility = `hidden`
          this.setTempData()
          this.windowsRemoveEventListener('pointermove', this.pointermove)
          this.windowsRemoveEventListener('pointerup', pointerup)
        }
        this.windowsAddEventListener('pointerup', pointerup)
      },
      pointerout (ev, node, data) {
        ev.returnValue = false
        if (ev.pointerType === 'touch') return

        if (!this.isPointerdown) return
        if (this.isPointerout) return
        console.log('pointerout')
        this.isPointerout = true

        let tree = this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree']
        tree.setChecked(data, true, true)

        // 获取所有的文件节点
        let transferData = tree
          .getCheckedNodes()
          .filter(x => x.FileType === 'file')

        this.cursor_text = `${transferData.length}个文件`

        // 获取所有的文件节点的父节点
        transferData.forEach(item => {
          let node = tree.getNode(item)
          if (!node.parent) return
          while ((node = node.parent)) {
            let pnode = node.data
            let isExist = transferData.some(
              _item => _item.NodeID === pnode.NodeID
            )
            if (!isExist) transferData.push(pnode)
            if (pnode.FileType === 'dir') break
          }
        })

        this.setTempData({
          type: 'juanzong',
          data: JSON.stringify(transferData)
        })
        this.windowsAddEventListener('pointermove', this.pointermove)
      },
      // dragStart(ev, node, data) {
      //   let tree = this.$refs[this.selected === 2 ? "dossierTree" : "docDossierTree"];
      //   tree.setChecked(data, true, true);
      //
      //   let transferData = JSON.parse(JSON.stringify(tree.getCheckedNodes().filter(x => "file" === x.FileType)));
      //
      //   if (this.isMergeDir) {
      //     let dataSrc = this.selected === 2 ? this.dossierDataSource : [];
      //     transferData.forEach(_data => {
      //       let Parent = dataSrc.filter(_node => _data.NodeParentID === _node.NodeID)[0];
      //
      //       _data.MLXSMC = Parent ? `${Parent.MLXSMC}(${_data.MLXSMC})` : _data.MLXSMC;
      //     });
      //   }
      //
      //   ev.dataTransfer.setData("text/plain", JSON.stringify(transferData));
      //   ev.dataTransfer.setData("type", "juanzong");
      // },
      renderContent (h, {node, data, store}) {
        return (
          <span
            class={'word14 node_' + data.NodeID}
            style="width:calc(100% - 46px);"
            // draggable
            // onDragstart={() => this.dragStart(event, node, data)}
            onPointerdown={() => this.pointerdown(event, node, data)}
            onPointerout={() => this.pointerout(event, node, data)}
          >
            {data.MLXSMC}
          </span>
        )
      },
      resize () {
        this.saveLayout()
      },
      saveLayout () {
        localStorage.setItem(
          'layoutConfig',
          JSON.stringify(this.pageData, null, 2)
        )
      },
      readLayout () {
        let layoutConfig = localStorage.getItem('layoutConfig')
        layoutConfig = JSON.parse(layoutConfig)
        if (
          layoutConfig &&
          layoutConfig.version === pageData.version &&
          layoutConfig.skin === pageData.skin
        ) {
          return (this.pageData = layoutConfig)
        }
        this.pageData = JSON.parse(JSON.stringify(pageData))
      },
      boxShow () {
      },
      resetSize () {
        this.pageData = JSON.parse(JSON.stringify(pageData))
      },
      clearChecked (type) {
        if (type === 'juanzong') {
          this.$refs[this.selected === 2 ? 'dossierTree' : 'docDossierTree'].setCheckedNodes([])
        }
        if (type === 'evidence') {
          this.$refs.evidenceCatalogTree.$refs.evidenceTree.setCheckedNodes([])
        }
      }
    }
  }

  let pageData = {
    version: skin[skin.useSkin].app.version,
    skin: skin.useSkin,
    name: 'outer',
    isHorizontal: true,
    showBar: true,
    bar: {
      style: {
        height: '100%',
        width: '30px',
        background: '#e0f5fb',
        'text-align': 'center',
        'border-right': '1px solid #a4d3ed',
        display: 'inline-block',
        border: '1px solid #bdd5e6'
      },
      options: {
        buttonList: [
          {
            name: 'container_left',
            innerText: '',
            innerHTML: '示<br>证<br>大<br>纲'
          },
          {
            name: 'container_center',
            innerText: '',
            innerHTML: '预<br>案<br>及<br>证<br>据'
          },
          {
            name: 'container_right',
            innerText: '',
            innerHTML: '证<br>据<br>编<br>辑'
          }
        ],
        buttonStyle: {
          'border-top': '0.5px #a4d3ed solid',
          'border-bottom': '0.5px #a4d3ed solid',
          height: '115px',
          display: 'block',
          'font-size': '14px',
          background: '#e0f5fb',
          color: '#0b609c'
        },
        buttonHoverStyle: {
          background: '#3787c1',
          color: '#fff',
          cursor: 'pointer'
        },
        position: 'left'
      }
    },
    hideButton: {
      style: {
        width: '39px',
        height: '39px',
        display: 'inline-block',
        position: 'absolute',
        'background-image': `url('${getBase64('/img/yc.png')}')`,
        // "background-color": "#eaf1f7",
        'background-repeat': 'no-repeat',
        'background-position': 'center',
        top: '1px',
        right: '1px',
        cursor: 'pointer',
        'z-index': '9'
      },
      options: {
        innerText: ''
      }
    },
    line: {
      style: {
        height: '100%',
        width: '10px',
        'vertical-align': 'top',
        display: 'inline-block',
        position: 'relative'
      },
      controlButtonStyle: {
        'text-align': 'center',
        'vertical-align': 'center',
        background:
          'url(\'\')',
        height: '25px',
        width: '10px',
        margin: 'auto',
        position: 'absolute',
        cursor: 'col-resize',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
      },
      options: {}
    },
    slots: [
      {
        name: 'container_left',
        style: {
          height: '100%',
          width: '229px',
          'vertical-align': 'top',
          'min-width': '220px',
          display: 'inline-block',
          overflow: 'hidden',
          position: 'relative'
        },
        options: {
          showHideButton: true,
          titleText: '最左边的',
          ratio: 0,
          hide: false
        }
      },
      {
        name: 'container_center',
        style: {
          height: '100%',
          width: '340px',
          'min-width': '290px',
          display: 'inline-block',
          overflow: 'hidden',
          position: 'relative'
        },
        options: {
          showTitle: false,
          showHideButton: true,
          titleText: '',
          ratio: 0,
          hide: false
        }
      },
      {
        name: 'container_right',
        style: {
          height: '100%',
          width: '839px',
          'vertical-align': 'top',
          'min-width': '100px',
          display: 'inline-block',
          overflow: 'hidden',
          position: 'relative'
        },
        options: {
          showHideButton: true,
          titleText: '最右边的',
          ratio: 1,
          hide: false
        }
      }
    ],
    title: {
      style: {
        overflow: 'hidden',
        'white-space': 'nowrap',
        'text-overflow': 'ellipsis'
      }
    }
  }
  pageData.slots.sort((slot1, slot2) => {
    return (
      skin[skin.useSkin].slot_sort[slot1.name] -
      skin[skin.useSkin].slot_sort[slot2.name]
    )
  })
</script>

<style scoped>
  .cursor_div {
    position: fixed;
    width: 100px;
    /*height: 50px;*/
    left: 0;
    top: 0;
    z-index: 999999;
    visibility: hidden;
    pointer-events: none;
    text-align: center;
  }

  .cursor_div .cursor_text {
    font-size: 12px;
    color: white;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.3);
    display: inline-block;
    padding-right: 10px;
    padding-left: 10px;
  }

  .cursor_div .cursor_img {
    height: 16px;
    width: 16px;
    background-size: 14px;
    margin-right: 5px;
    display: inline-block;
    background-position: center;
    background-repeat: no-repeat;
    /*margin-left: 20px;*/
  }

  .slot_item {
    height: 100%;
    width: 100%;
    overflow: hidden;
    border: 1px solid #bdd5e6;
    border-top: none;
    border-bottom: none;
  }

  .nav {
    height: 40px;
    width: 100%;
    background-color: #e7f2f6;
    border-bottom: solid 1px #9aadb9;
    position: relative;
  }

  .nav .nav_item {
    display: inline-block;
    font-size: 15px;
    width: 80px;
    color: #7ba3bf;
    text-align: center;
    height: 35px;
    line-height: 35px;
    margin-top: 5px;
  }

  .nav .nav_item:nth-child(1) {
    margin-left: 5px;
  }

  .nav .nav_item:hover {
    color: #157ac1;
  }

  .nav_right {
    height: 40px;
    width: 100%;
    background-color: #e7f2f6;
    border-bottom: solid 1px #9aadb9;
    position: relative;
  }

  .nav_right_item {
    display: inline-block;
    font-size: 15px !important;
    width: 100px;
    color: #7ba3bf;
    text-align: center;
    height: 35px;
    line-height: 35px;
    margin-top: 5px;
  }

  .nav_right_item:nth-child(1) {
    margin-left: 5px;
  }

  .nav_right_item_selected {
    background-color: #f2f9fc;
    color: #157ac1;
    border: solid 1px #9aadb9;
    border-bottom: none;
  }

  .nav_right_item:hover {
    color: #157ac1;
  }

  .dossierTree {
    height: calc(100% - 40px);
    overflow: auto;
  }

  .btn_control {
    position: absolute;
    top: 50%;
    width: 40px;
    height: 40px;
    cursor: pointer;
    transform: translate(0, -50%);
    background-size: 100% 100% !important;
    opacity: 0.3;
  }

  .btn_control:hover {
    opacity: 1;
  }

  .btn_control.left {
    left: 30px;
    background: url("~@/assets/img/yuan/pdfLeft.png");
  }

  .btn_control.right {
    right: 30px;
    background: url("~@/assets/img/yuan/pdfRight.png");
  }
</style>
